# --**coding:utf-8**--
# Create by author: hemq
from channel.python import Const, Util, androidTools
import qrcode
from PIL import Image


def getAChannelApk(name_apk_base, channel_id):
    '''
    修改包渠道号
    '''
    # 对渠道号文件进行修改 Const.PATH_APK_FILE_SOURCEID为apk解压后一文件路径
    Util.changeChannel(Const.PATH_APK_FILE_SOURCEID, channel_id)
    print Const.PATH_APK_FILE_SOURCEID
    print channel_id

    # 直接在APK文件中修改渠道号
    androidTools.zipAddFile(name_apk_base, Const.PATH_APK_FILE_SOURCEID)
    print name_apk_base
    print Const.PATH_APK_FILE_SOURCEID
    # 对未签名的APK包，进行签名

    # androidTools.SignApk(Const.BASE_NAME_APKUNALIGN,name_apk_base,Const.PATH_KEYSTORE,Const.NAME_KEYSTORE,Const.SIGN_KEYPASSWD)


#    androidTools.SignApk(path_apk_channel,name_apk_base,PATH_KEYSTORE,NAME_KEYSTORE,SIGN_KEYPASSWD)
#    androidTools.zipalign(Const.BASE_NAME_APKUNALIGN,path_apk_channel)

def createQRCode(url, channelName, channelNum):
    '''
    根据对应apk生成对应二维码
    '''
    # 需要生成二维码的URL
    url = url
    # 命名二维码
    name_img = "JDBClient_%s_%s.png" % (channelName, channelNum)

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=2,
        border=1
    )
    qr.add_data(url)
    qr.make(fit=True)

    img = qr.make_image()
    img = img.convert("RGBA")

    # 二维码中添加icon图片，若有，则添加
    '''
    icon = Image.open("%s" % jdb_base_data.jdb_icon)

    img_w, img_h = img.size
    factor = 4
    size_w = int(img_w / factor)
    size_h = int(img_h / factor)

    icon_w, icon_h = icon.size
    if icon_w > size_w:
        icon_w = size_w
    if icon_h > size_h:
        icon_h = size_h
    icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

    w = int((img_w - icon_w) / 2)
    h = int((img_h - icon_h) / 2)
    img.paste(icon, (w, h), icon)
    
    '''
    img.save(name_img)


def SignApk(keyStorePath, signPassword, signApkPath, channelApkPath, alias):
    """
    对未签名的APK包，进行签名
     jarsigner -verbose -keystore keystore文件路径 -signedjar 签名后生成的apk路径 待签名的apk路径 别名
    """
    cmd = 'jarsigner -verbose -keystore' + keyStorePath + '-storepass' + ' ' + signPassword + '-signedjar' + signApkPath + ' ' + channelApkPath + ' ' + alias

    cmd1 = '/data/jdk/bin/jarsigner -verbose  -sigalg MD5withRSA -digestalg SHA1 -keystore ' + keyStorePath + ' -storepass ' + signPassword + ' -signedjar ' + signApkPath + ' ' + channelApkPath + ' ' + alias
    # cmd = '/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home/bin/jarsigner -verbose  -sigalg MD5withRSA -digestalg SHA1 -keystore '+ path_keystore +' -storepass '+ sign_passwd +' -signedjar '+signApk+' '+ unsignApk +' ' + name_keystore

    Util.ExecCmd(cmd)
